import { ThemeMode } from '@/enums'
import { create } from 'zustand'

interface ThemeState {
  theme: ThemeMode
  toggleTheme: (mode?: ThemeMode) => void
  initTheme: () => void
}

export const useThemeStore = create<ThemeState>()((set, get) => ({
  theme: ThemeMode.LIGHT, // 默认亮色模式

  toggleTheme: (mode?: ThemeMode) => {
    const { theme } = get()
    const next = mode || (theme === ThemeMode.DARK ? ThemeMode.LIGHT : ThemeMode.DARK)
    document.documentElement.classList.remove(theme)
    document.documentElement.classList.add(next)
    set({ theme: next })
    window.baseApi.setTheme(next)
  },

  initTheme: async () => {
    try {
      const theme = (await window.baseApi.getTheme()) as ThemeMode
      document.documentElement.className = theme
      await window.baseApi.setTheme(theme)
    } catch (e) {
      console.error('获取主题失败', e)
    }
  }
}))
